import { reactive } from "vue";
var ac = null;//联想类
// 自动定位
function getUserPosition() {
  let address = reactive({
    addresName: "定位中...",
    position: ""
  });
  var geolocation = new BMap.Geolocation();
  geolocation.enableSDKLocation();
  geolocation.getCurrentPosition(function (r) {
    if (this.getStatus() == BMAP_STATUS_SUCCESS) {
      const { province, city } = r.address;
      address.addresName = province + city;
      address.position = r.point;
    } else {
      throw new Error("failed" + this.getStatus())
    }
  });
  return address;
}
//初始化地图
function initMap(el, position, zoom = 14) {
  var map = new BMap.Map(el);
  var point = new BMap.Point(position.lng, position.lat);
  map.centerAndZoom(point, zoom);
  map.enableScrollWheelZoom();
  map.panTo(point);
  window.mapInstance = map;
}
// 根据ip解析地址
function accordingIpCity(position , callBack) {
    var point = new BMap.Point(position.lng, position.lat);
    var gc = new BMap.Geocoder();
    gc.getLocation(point, function (rs) {
      var addComp = rs.addressComponents;
      callBack(addComp);
    });
}

// 根据名称转换成经纬度

function accprdingCityNamePostion(name, callBack) {
  var myGeo = new BMap.Geocoder();
  myGeo.getPoint(name, (point) => {
    console.log(point);
      if(point){
        callBack(point);
      }else {
        alert("请输入正确的地址描述");
      }
  });
}

export { getUserPosition, initMap, accordingIpCity, accprdingCityNamePostion };
